package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.AddroleDto;
import com.zzyl.dto.RolepageDto;
import com.zzyl.dto.updateDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapp;
import com.zzyl.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.zzyl.constant.SuperConstant.DATA_STATE_0;
import static com.zzyl.constant.SuperConstant.DATA_STATE_1;

@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
     private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private UserRoleMapp userRoleMapp;



    @Override
    public PageResponse<Role> page(Integer pageNum, Integer pageSize, RolepageDto dto) {
        //开启分页
       PageHelper.startPage(pageNum==null?1:pageNum,pageSize==null?10:pageSize);
        Page<Role>page = roleMapper.page(dto);
        return  PageResponse.of(page, Role.class);
    }

    public void addRole (AddroleDto dto) {
       //判断的用户名是否重复
        Role role = roleMapper.selectByName(dto.getRoleName());
        if(role!=null){
            throw new RuntimeException("角色名已存在");
        }
        //保存
        Role role1 = BeanUtil.copyProperties(dto, Role.class);
        role1.setSortNo(1);
        roleMapper.insertSelective(role1);

    }

    @Override
    public List<String> findCheckedResources(Long roleId) {

        return roleResourceMapper.findCheckedResources(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(updateDto dto) {

        //判断用户名是否重复
        Role role1 = roleMapper.selectByName(dto.getRoleName());
        if(role1==null){
        }else {
            if(Objects.equals(role1.getId(),dto.getId())){

            } else {
                throw new BaseException(BasicEnum.DATA_EXIST);
            }
        }

            //处理处理启用和禁用 dot.dotoState==0启用 dot.dotoState==1禁用
            role1 = roleMapper.selectByPrimaryKey(dto.getId());
           if (role1==null){
             throw new BaseException(BasicEnum.DATA_NOT_EXIST);
        }
           //说明修改状态
        if(!Objects.equals(role1.getDataState(),dto.getDataState())){
            //如果是禁用，判断是否关联到了用户
            if(Objects.equals(dto.getDataState(), SuperConstant.DATA_STATE_1)){
                List<UserRole> userRoles = userRoleMapp.selectByRole(dto.getId());
                if(!CollectionUtils.isEmpty(userRoles)){
                    throw new BaseException(BasicEnum.USER_ROLE_RELATED);
                }
            }
        }


        //保存
        Role role = BeanUtil.copyProperties(dto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        // 没操作资源
        if(dto.getCheckedResourceNos() == null){
            return;
        }
        //删除关联关系
        roleResourceMapper.deleteByRoleId(dto.getId());
      /*  //插入新的关联关系
        List<RoleResource> roleResources =new ArrayList<>();
        if(!CollectionUtil.isEmpty(dto.getCheckedDeptNos())){
            for (String resourceNo :dto.getCheckedDeptNos()) {
                RoleResource rr = new RoleResource();
                rr.setRoleId(dto.getId());
                rr.setResourceNo(resourceNo);
                rr.setDataState(DATA_STATE_0);
                roleResources.add(rr);
            }*/

            // 插入新的关联关系
            if(!CollectionUtils.isEmpty(dto.getCheckedResourceNos())){
                List<RoleResource> roleResources = dto.getCheckedResourceNos().stream().map(resourceNo -> {
                    RoleResource rr = new RoleResource();
                    rr.setRoleId(dto.getId());
                    rr.setResourceNo(resourceNo);
                    rr.setDataState(DATA_STATE_0);
                    return rr;
                }).collect(Collectors.toList());
                roleResourceMapper.batchInsert(roleResources);



            roleResourceMapper.batchInsert(roleResources);

        }



    }

    @Override
    public void deleteRole(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role==null){
            throw new BaseException(BasicEnum.DATA_NOT_EXIST);

    }
        //判断是否启用禁用

       if(Objects.equals(role.getDataState(),DATA_STATE_0)){
           throw  new RuntimeException("职位已启用，不能删除");
       }
        //删除
        roleMapper.deleteByPrimaryKey(id);
       //删除role -resource
        roleResourceMapper.deleteByRoleId(id);
    }

    @Override
    public List<Role> list() {
            return  roleMapper.selectRoleByStatus(DATA_STATE_0);
    }
}

